﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Web;

namespace ezCloud.Api.Common
{
    public class MemoryCacher
    {
        public static Dictionary<int, StringCollection> cacheByHotelId = new Dictionary<int, StringCollection>();
        public object GetValue(string key)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            return memoryCache.Get(key);
        }

        public bool Add(string key, object value, DateTimeOffset absExpiration)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            return memoryCache.Add(key, value, absExpiration);
        }

        public bool AddByHotelId(int hotelId, string key, object value, DateTimeOffset absExpiration)
        {
            StringCollection collection;
            if (cacheByHotelId.ContainsKey(hotelId))
            {
                collection = cacheByHotelId[hotelId];
            } else
            {
                collection = new StringCollection();
                cacheByHotelId.Add(hotelId, collection);
            }
            if (!collection.Contains(key))
                collection.Add(key);
            MemoryCache memoryCache = MemoryCache.Default;
            return memoryCache.Add(key, value, absExpiration);
        }
        public void Delete(string key)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            if (memoryCache.Contains(key))
            {
                memoryCache.Remove(key);
            }
        }
        public static void ClearStatusCache(int hotelId)
        {
            var key = "STATUS_" + hotelId;
            MemoryCache memoryCache = MemoryCache.Default;
            if (memoryCache.Contains(key))
            {
                memoryCache.Remove(key);
            }
            //clear collection
            if (cacheByHotelId.ContainsKey(hotelId))
            {
                var collection = cacheByHotelId[hotelId];
                foreach(string k in collection)
                {
                    if (memoryCache.Contains(k))
                    {
                        memoryCache.Remove(k);
                    }
                }
                cacheByHotelId.Remove(hotelId);
            }
        }
    }
}